package com.fsp.blog.service.iml;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fsp.blog.dao.ArticleBodyMapper;
import com.fsp.blog.dao.ArticleMapper;
import com.fsp.blog.dao.ArticleTagMapper;
import com.fsp.blog.dao.dos.Archives;
import com.fsp.blog.pojo.Article;
import com.fsp.blog.pojo.ArticleBody;
import com.fsp.blog.pojo.ArticleTag;
import com.fsp.blog.pojo.SysUser;
import com.fsp.blog.service.*;
import com.fsp.blog.utils.UserThreadLocal;
import com.fsp.blog.vo.ArticleBodyVo;
import com.fsp.blog.vo.ArticleVo;
import com.fsp.blog.vo.Result;
import com.fsp.blog.vo.TagVo;
import com.fsp.blog.vo.params.ArticleParam;
import com.fsp.blog.vo.params.PageParams;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fushengping
 * @className ArticleServiceImpl
 * @description
 * @date 2021/11/4 23:53
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Resource
    private ArticleTagMapper articleTagMapper;

    @Autowired
    private TagsService tagsService;

    @Autowired
    private SysUserService sysUserService;

    @Override
    public Result listArticlesPage(PageParams pageParams) {
        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
        IPage<Article> articleIPage = articleMapper.listArticle(
                page,
                pageParams.getCategoryId(),
                pageParams.getTagId(),
                pageParams.getYear(),
                pageParams.getMonth());
        List<Article> records = articleIPage.getRecords();
        return Result.success(copyList(records,true,true));
    }

//    @Override
//    public Result listArticlesPage(PageParams pageParams) {
//        //分页查询需要传入new Page()和查询条件
//        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
//        if (pageParams.getCategoryId() != null) {
//            //sql:  and category_id = #{categoryId}
//            queryWrapper.eq(Article::getCategoryId,pageParams.getCategoryId());
//        }
//        List<Long> articleTagsList = new ArrayList<>();
//        if (pageParams.getTagId() != null) {
//            // 加入标签  条件查询
//            /**
//             * 由于article表中没有tagId字段，通过中间表可进行查询
//             * article_tag表中:  articleId n 对 1  tagId
//             */
//            LambdaQueryWrapper<ArticleTag> articleTagLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            articleTagLambdaQueryWrapper.eq(ArticleTag::getTagId,pageParams.getTagId());
//            List<ArticleTag> articleTags = articleTagMapper.selectList(articleTagLambdaQueryWrapper);
//            for (ArticleTag articleTag : articleTags) {
//                articleTagsList.add(articleTag.getArticleId()); //存放该标签关联的文章id
//            }
//            if (articleTagsList.size() > 0) {
//                //sql:  and articleId in (1,2,3)
//                queryWrapper.in(Article::getId,articleTagsList);
//            }
//
//        }
//        //mybatis-plus拦截器的page
//        Page<Article> page = new Page<>(pageParams.getPage(),pageParams.getPageSize());
//        /*是否置顶，进行排序，对article表的with、时间字段进行排序--order by CreateDate desc */
//        queryWrapper.orderByDesc(Article::getWeight,Article::getCreateDate);
//        //添加page和条件
//        Page<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
//        //使用getRecords转成List<E>
//        List<Article> records = articlePage.getRecords();
//        //将其转化为包含tagVo的articleVo对象
//        List<ArticleVo> articleVoList = copyList(records,true,true);
//        return Result.success(articleVoList);
//    }

    @Override
    public Result hotArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //对浏览量进行排序(倒序)  ::表示方法引用
        queryWrapper.orderByDesc(Article::getViewCounts);
        //对排序后最热文章的数据进行获取
        queryWrapper.select(Article::getId,Article::getTitle);
        //对limit - 进行拼接查询
        queryWrapper.last("limit "+ limit);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articles,false,false));
    }

    @Override
    public Result newArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //对创建时间进行排序
        queryWrapper.orderByDesc(Article::getCreateDate);
        //对排完序的最新文章进行取数
        queryWrapper.select(Article::getId,Article::getTitle);
        //进行limit拼接查询
        queryWrapper.last("limit "+ limit);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articles,false,false));
    }

    @Override
    public Result listArchives() {
        List<Archives> archivesList =articleMapper.listArchives();
        return Result.success(archivesList);
    }

    //线程池操作
    @Autowired
    private ThreadService threadService;

    @Override
    public Result findArticleById(Long articleId) {
        /**
         * 1.根据id查询文章信息
         * 2.根据bodyId和categoryId做关联查询
         */
        Article article = articleMapper.selectById(articleId);
        ArticleVo articleVo = copy(article, true, true,true,true);
        /*看完文章之后，本应直接返回数据，但是看完文章月度数加1进行更新，
          更新时加写锁，阻塞其他的读操作，新能较低
        * 更新增加了此次接口的耗时, 一旦更新出问题，不影响查看
          使用线程池, 更新操作扔到线程池执行，和主线程无关
        */
        threadService.updateArticleVieCount(articleMapper,article);
        return Result.success(articleVo);
    }

    @Override
    public Result publish(ArticleParam articleParam) {
        SysUser sysUser = UserThreadLocal.get(); //从主线程中获取用户信息，该接口需放于拦截器中
        /**
         * 1.发布文章，构建文章对象Article
         * 2.作者id  当前登录用户
         * 3.标签  要将标签插入关联表中
         * 4.body 内容存储  与article表互相关联
         */
        //构建文章对象
        Article article = new Article();
        article.setAuthorId(sysUser.getId());
        article.setWeight(Article.Article_Common);
        article.setViewCounts(0);
        article.setCommentCounts(0);
        article.setSummary(articleParam.getSummary());
        article.setTitle(articleParam.getTitle());
        article.setCategoryId(articleParam.getCategory().getId());
        article.setCreateDate(System.currentTimeMillis());
        this.articleMapper.insert(article);//插入之后会生成一个文章id
        //tag
        List<TagVo> tags = articleParam.getTags();
        if (tags != null) { //articleTag关联表插入数据
            for (TagVo tag : tags) {
                Long articleId = article.getId();
                Long tagId = tag.getId();
                ArticleTag articleTag = new ArticleTag();
                articleTag.setArticleId(articleId);
                articleTag.setTagId(tagId);
                articleTagMapper.insert(articleTag);
            }
        }
        //articleBody
        ArticleBody articleBody = new ArticleBody();
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBody.setArticleId(article.getId());
        articleBodyMapper.insert(articleBody);

        //由于article表与body表互相关联存有对方id,对article对象进行更新
        article.setBodyId(articleBody.getId());
        articleMapper.updateById(article);

        //返回一个id的map
        Map<String, String> map = new HashMap<>();
        map.put("id",article.getId().toString()); //转化为String是为了防止精度损失
        return Result.success(map);
    }

    private List<ArticleVo> copyList(List<Article> records, boolean isTags, boolean isAuthor) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record,isTags,isAuthor,false,false));
        }
        return articleVoList;
    }
    /*方法重载,实现不同需求的copy*/
    private List<ArticleVo> copyList(List<Article> records, boolean isTags, boolean isAuthor, boolean isBody, boolean isCategory) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record,isTags,isAuthor,isBody,isCategory));
        }
        return articleVoList;
    }

    @Autowired
    private CategoryService categoryService;

    /*将Article分解转移成ArticleVo相对应的属性*/
    private ArticleVo copy(Article article, boolean isTags, boolean isAuthor, boolean isBody, boolean isCategory) {
        ArticleVo articleVo = new ArticleVo();
        //使用spring自带的copy拷贝
        BeanUtils.copyProperties(article,articleVo);
        //如果两个类有字段属性不同，如这里的createDate不同
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH: mm"));
        /*并不是所有的文章都需要标签和作者信息，这里不是article的表中的数据,不属于article的service*/
        if (isTags) {
            //需要拿到文章的id,进而存入文章的标签tag
            Long articleId = article.getId();
            articleVo.setTags(tagsService.findTagsByArticleId(articleId));
        }
        if (isAuthor) {
            Long authorId = article.getAuthorId();
            articleVo.setAuthor(sysUserService.findUserById(authorId).getNickname());
        }
        if (isBody) {
            Long bodyId = article.getBodyId();
            articleVo.setBody(findArticeBodyById(bodyId));
        }
        if (isCategory) {
            Long categoryId = article.getCategoryId();
            articleVo.setCategory(categoryService.findCategoryById(categoryId));
        }
        return articleVo;
    }

    @Resource
    private ArticleBodyMapper articleBodyMapper;

    private ArticleBodyVo findArticeBodyById(Long bodyId) {
        ArticleBody articleBody = articleBodyMapper.selectById(bodyId);
        ArticleBodyVo articleBodyVo = new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContent());
        return articleBodyVo;
    }
}
